package com.whut.mobilesafe.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.whut.mobilesafe.R;
import com.whut.mobilesafe.domain.VersionInFo;
import com.whut.mobilesafe.thirdpart.ProgressDownLoadFile;
import com.whut.mobilesafe.utils.Json2Object;
import com.whut.mobilesafe.utils.Stream2String;

import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;



public class SplashActivity extends Activity {
    /**
     * 下面列举的是几个子线程向主线程发送的状态码
     */


    private static final int STATE_URL_EXCEPTION = 1;
    private static final int STATE_IO_EXCEPTION = 2;
    private static final int STATE_JSON_EXCEPTION = 3;
    private static final int STATE_NEED_UPDATE = 4;
    private static final int STATE_ENTER_HOME = 5;

    private TextView tvVersion;
    private TextView tvProgress;

    private VersionInFo inFo;//服务器端传过来的更新版本信息

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case STATE_URL_EXCEPTION:
                    Toast.makeText(SplashActivity.this, "url链接发生了错误", Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case STATE_IO_EXCEPTION:
                    Toast.makeText(SplashActivity.this, "IO异常", Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case STATE_JSON_EXCEPTION:
                    Toast.makeText(SplashActivity.this, "json字符串传输错误", Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case STATE_ENTER_HOME:
                    enterHome();
                    break;
                case STATE_NEED_UPDATE:
                    inFo = (VersionInFo) msg.obj;
                    tvVersion.setText("当前版本号:" + getPackageInFoName());
                    showUpdateDialog();
                    break;
            }
        }
    };

    /**
     * 显示升级对话框
     */
    private void showUpdateDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("升级通知");
        builder.setMessage(inFo.getDes());
        builder.setPositiveButton("马上升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                downLoadApk();
            }
        });

        builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                enterHome();
            }
        });
        //升级弹窗不可取消
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 下载更新最新版的apk,尝试使用okhttp
     */
    private void downLoadApk() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            tvProgress.setVisibility(View.VISIBLE);
            String path = Environment.getExternalStorageDirectory().getAbsolutePath();
            String url = inFo.getUrl();
            downLoad(path, url);
        } else {
            Toast.makeText(SplashActivity.this, "SDcard的有问题呦", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        //去掉标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash);

        tvVersion = (TextView) findViewById(R.id.tv_version);
        tvProgress = (TextView) findViewById(R.id.tv_progress);

        //子线程从去访问服务器获取版本信息
        getServerVersion();
    }

    /**
     * 获取服务器端版本号判断是否要更新
     */
    private void getServerVersion() {
        /**
         * 先让splashActivity展示3秒种
         * 获取服务器端信息，判断是否需要更新
         * 然后给主线程发消息 更新页面 完成跳转
         */
        Thread thread = new Thread() {
            @Override
            public void run() {
                SystemClock.sleep(3000);
                Message msg = Message.obtain();
                HttpURLConnection httpURLConnection = null;
                try {
                    URL url = new URL("http://10.139.34.158:8081/Demo/update.json");
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    //连接超时
                    httpURLConnection.setConnectTimeout(2000);
                    //连接上了，读取超时。因为服务器不给反映
                    httpURLConnection.setReadTimeout(2000);
                    InputStream inputStream = httpURLConnection.getInputStream();

                    String inFo = Stream2String.getStringInFo(inputStream);
                    VersionInFo verInfo = Json2Object.getVerInfo(inFo);

                    //如果当前应用的版本号小于服务器端版本号说明需要更新了
                    if (getPackageInFo() < verInfo.getVersionCode()) {
                        msg.what = STATE_NEED_UPDATE;
                        msg.obj = verInfo;
                    } else {
                        msg.what = STATE_ENTER_HOME;
                    }

                } catch (JSONException e) {
                    msg.what = STATE_JSON_EXCEPTION;
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    msg.what = STATE_URL_EXCEPTION;
                    e.printStackTrace();
                } catch (Exception e) {
                    msg.what = STATE_IO_EXCEPTION;
                    e.printStackTrace();
                } finally {
                    mHandler.sendMessage(msg);
                }
            }
        };
        thread.start();
    }


    /**
     * 获取当前应用的版本号
     */
    public int getPackageInFo() {
        int versionCode = -1;
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取当前应用的版本名
     */
    public String getPackageInFoName() {
        String versionName = "";
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 进入主界面
     */

    public void enterHome() {
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }


    /**
     * 下载apk
     *
     * @param path 将apk下载到哪个位置
     * @param url  请求的服务器路径
     */
    public void downLoad(final String path, String url) {
        OkHttpClient client = new OkHttpClient();
        //监听下载进度
        final ProgressDownLoadFile.ProgressListener progressListener = new ProgressDownLoadFile.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                final int percent = (100 * (int) bytesRead) / (int) contentLength;
                System.out.format("%d%% done\n", percent);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvProgress.setText("当前进度:" + percent + " % ");
                    }
                });
            }
        };
        //添加拦截器，自定义ResponseBody，添加下载进度
        client.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originResponse = chain.proceed(chain.request());
                return originResponse.newBuilder().body(
                        new ProgressDownLoadFile.ProgressResponseBody(originResponse.body(), progressListener))
                        .build();
            }
        });

        Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            //当请求失败的时候
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
            }

            //当请求成功的时候
            @Override
            public void onResponse(Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                InputStream is = null;
                File file = new File(path, "mobilesafe.apk");
                FileOutputStream fos = new FileOutputStream(file);
                is = response.body().byteStream();
                int len = 0;
                byte[] data = new byte[1024];
                while ((len = is.read(data)) != -1) {
                    fos.write(data, 0, len);
                }

                is.close();
                fos.close();

                installApk(file);
            }
        });
    }


    /**
     * 从下载下来的包的位置去安装apk
     *
     * @param packageFile
     */
    public void installApk(File packageFile) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setDataAndType(Uri.fromFile(packageFile),
                "application/vnd.android.package-archive");
        //进入主界面
        enterHome();
    }
}
